package com.gaotu.ci;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.json.JSONObject;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.gaotu.handler.MailServiceIHandler;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class QingzhouNoticeJobHandler extends IJobHandler {
    @Resource
    private MailServiceIHandler mailServiceIHandler;

    public static void main(String[] args) {
        try {
            new QingzhouNoticeJobHandler().execute(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

    /**
     * 参数格式
     * {
     * "day":7,
     * "course": true,
     * "order" : true
     * }
     *
     * @param param 参数
     */
    @Override
    public ReturnT<String> execute(String param) throws Exception {
        com.alibaba.fastjson.JSONObject params = JSON.parseObject(param);
        Integer day = params.getInteger("day");

        Boolean order = params.getBoolean("order");
        Boolean course = params.getBoolean("course");
        //新建一个工作簿
        Workbook workbook = new HSSFWorkbook();


        String fileName = "notice" + System.currentTimeMillis() / 1000 + ".xls";
        LocalDateTime now = LocalDateTime.now();

        long end = now.toEpochSecond(ZoneOffset.of("+8"));

        LocalDateTime startTime = now.minusWeeks(1).plusHours(4);

        long start = startTime.toEpochSecond(ZoneOffset.of("+8"));
        if (day != null && day != 0) {
            startTime = now.minusDays(day);
            start = startTime.toEpochSecond(ZoneOffset.of("+8"));
        }

        if (course) {
            Sheet courseSheet = workbook.createSheet("course");
            List<String> apps =
                    Arrays.asList("course-setting", "baijia.gt.ecommerce.product.course-setting-task", "teacher-basic",
                            "baijia.gaotu.tech.backend.teacher-basic-task");
            getAndSendNoticeExcel(workbook, courseSheet, fileName, now, end, startTime, start, apps);
        }
        if (order) {
            Sheet orderSheet = workbook.createSheet("order");
            List<String> apps2 = Arrays.asList("gaotu_order", "gaotu_order_task", "baijia.gaotu.tech.trade.order-ad",
                    "baijia.gaotu.tech.trade.order-b", "gaotu_coupon_a",
                    "baijia.gaotu.Shared.market.gaotu-coupon-a-task",
                    "gaotu_coupon_c", "baijia.gaotu.Shared.market.gaotu-coupon-c-task", "gaotu_coupon_management",
                    "baijia.gaotu.Shared.market.gaotu-coupon-management-task", "gaotu_market", "gaotu_promotion",
                    "gaotu_promotion_c", "baijia.gaotu.Shared.market.gaotu-promotion-task",
                    "gaotu_promotion_management",
                    "gaotu_rule", "promotion-app", "gaotu_cart");
            getAndSendNoticeExcel(workbook, orderSheet, fileName, now, end, startTime, start, apps2);
        }
        return ReturnT.SUCCESS;
    }

    private void getAndSendNoticeExcel(Workbook workbook, Sheet sheet, String fileName, LocalDateTime now, long end,
            LocalDateTime startTime, long start, List<String> apps) {
        getNotice(sheet, start, end, apps, null);
        byte[] excel = getExcel(workbook, fileName);
        String copyMail = "JSB-PTJSB-DSJSB-JYZ@baijia.com";
        String title = startTime.format(formatter) + "-" + now.format(formatter) + "轻舟告警信息汇总";
        sendEmail(mailServiceIHandler, fileName, title, apps, excel, copyMail);
    }

    private static void sendEmail(MailServiceIHandler mailSender, String fileName, String title,
            List<String> apps, byte[] excel, String copyMail) {
        if (null == excel || excel.length == 0) {
            XxlJobLogger.log("输入流为空");
            return;
        }

        mailSender.sendMsgFileDs("wangziyang@baijia.com", copyMail, title, "结果见附件,服务列表" + JSON.toJSONString(apps),
                fileName,
                new ByteArrayInputStream(excel));
    }

    private static byte[] getExcel(Workbook workbook, String fileName) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            FileOutputStream fout = new FileOutputStream("notice" + System.currentTimeMillis() / 1000 + ".xls");
            workbook.write(fout);
            workbook.write(out);

            fout.close();
            //            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }

    private static void getNotice(Sheet sheet, long start, long end, List<String> apps, String cookie) {
        JSONObject jo = new JSONObject();


        jo.put("appIds", apps)
                .put("startTime", start * 1000)
                .put("endTime", end * 1000)
                .put("pageDto", new JSONObject().put("pageNum", 1).put("pageSize", 1000));


        String response = null;
        try {
            response = Unirest.post(
                    "http://qingzhou.baijia.com/qingzhou/tianyan/alarmcenter/alarminfo/query")
                    //                    .header("Cookie", cookie)
                    .header("Content-Type", "application/json")
                    .body(jo).asString().getBody();
        } catch (UnirestException e) {
            e.printStackTrace();
        }
        com.alibaba.fastjson.JSONArray data = JSON.parseObject(response).getJSONArray("data");


        List<String> header =
                Arrays.asList("alarmTime", "appId", "alarmLevelName", "alarmRule", "alarmKeyword", "alarmInfo");
        int r = 0;
        Row first = sheet.createRow(r++);
        for (int j = 0; j < header.size(); j++) {
            Cell cell = first.createCell(j);
            cell.setCellValue(header.get(j));
        }
        for (int i = 0; i < data.size(); i++) {
            com.alibaba.fastjson.JSONObject oneNotice = data.getJSONObject(i);
            if ("通知".equals(oneNotice.getString("alarmLevelName"))) {
                continue;
            }
            Row row = sheet.createRow(r++);

            for (int j = 0; j < header.size(); j++) {
				
                Cell cell = row.createCell(j);
              	if(j==0){
                  cell.setCellValue(oneNotice.getString(header.get(j)));
                }else{
                  cell.setCellValue(oneNotice.getString(header.get(j)));
                }
            }
        }


    }
  
  	private static String safeDateTimeFormat(String time) throws Exception {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.format(new Date(Long.parseLong(time)));
        } catch (Exception e) {
            return time;
        }
    }

}
